package com.its.myalgorithm.day02;

/**
 * 数组前缀和
 */
public class PreSum {
    /**
     * 遍历
     */
    public static class RangeSum1 {

        private int[] arr;

        public RangeSum1(int[] array) {
            arr = array;
        }

        public int rangeSum(int L, int R) {
            int sum = 0;
            for (int i = L; i <= R; i++) {
                sum += arr[i];
            }
            return sum;
        }

    }
    /**
     * 方案2：
     * 1. 借H数组 把arr中的前缀和累加 得到新的数组
     * 2. 求l-r的累加和 l!=0;arr[r]-arr[l-1] l=0;arr[r]
     */
    public static class RangeSum2 {

        private int[] preSum;

        public RangeSum2(int[] array) {
            int N = array.length;
            preSum = new int[N];
            preSum[0] = array[0];
            for (int i = 1; i < N; i++) {
                preSum[i] = preSum[i - 1] + array[i];
            }
        }

        public int rangeSum(int L, int R) {
            return L == 0 ? preSum[R] : preSum[R] - preSum[L - 1];
        }

    }

}
